package com.lt.bcra.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lt.bcra.entity.BcraCategory;
import com.lt.bcra.entity.BcraDictionary;
import com.lt.bcra.exception.BaseException;
import com.lt.bcra.mapper.BcraCategoryMapper;
import com.lt.bcra.result.ResponseEnum;
import com.lt.bcra.result.ResultData;
import com.lt.bcra.service.BcraCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lt.bcra.service.BcraDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LuoTian
 * @since 2022-05-30
 */
@Service
public class BcraCategoryServiceImpl extends ServiceImpl<BcraCategoryMapper, BcraCategory> implements BcraCategoryService {

    @Autowired
    BcraCategoryMapper bcraCategoryMapper;

    @Autowired
    BcraDictionaryService bcraDictionaryService;

    @Override
    public ResultData deleteCategory(Integer id) {
        int deleteById = bcraCategoryMapper.deleteById(id);
        //删除对应种类的所有字典数据
        QueryWrapper<BcraDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", id);
        boolean remove = bcraDictionaryService.remove(queryWrapper);

        if (deleteById != 1 || remove == false) {
            throw new BaseException(ResponseEnum.DELETE_DATA_ERROR);
        }
        List<Object> list = new ArrayList<>();
        list.add(deleteById);
        list.add(remove);
        return ResultData.getResult(list);
    }

    @Override
    public ResultData saveCategory(BcraCategory bcraCategory) {
        String category = bcraCategory.getCategory();
        String code = bcraCategory.getCode();

        QueryWrapper<BcraCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category", category);
        if (bcraCategoryMapper.selectOne(queryWrapper)!=null){
            throw new BaseException(ResponseEnum.CATEGORY_SAME_ERROR);
        }

        QueryWrapper<BcraCategory> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("code", code);
        if (bcraCategoryMapper.selectOne(queryWrapper1)!=null){
            throw new BaseException(ResponseEnum.CODE_SAME_ERROR);
        }

        int insert = bcraCategoryMapper.insert(bcraCategory);
        return ResultData.getResult(insert);
    }
}
